
 <template>
 	<div>
 		<el-upload :file-list="fileLists" :action="uploadAction" :before-upload="handleBeforeUpload" :headers="headers"
 			:on-error="handleUploadError" :on-success="handleUploadSuccess" list-type="picture-card"
 			class="avatar-uploader" :on-remove="handleDel" :on-preview="handlePictureCardPreview">
 			<i class="el-icon-plus avatar-uploader-icon"></i>
 		</el-upload>
 		<el-dialog :visible.sync="dialogVisible">
 			<img :src="dialogImageUrl" width="450">
 		</el-dialog>
 	</div>
 </template>
 
 <script>
 	// 支持双向数据绑定，采用:src.sync
 	// 支持$emit事件success,处理复杂上传成功回调函数
 	import axios from 'axios';
 	export default {
 		name: 'lot-upload',
 		props: {
 			fileLists: {
 				type: Array,
 			},
 			defaultImage: {
 				type: String
 			},
 			uploadAction: {
 				type: String,
 				required: true
 			},
 			removeAction: {
 				type: String,
 				required: true
 			},
 			data: {
 				type: Object
 			},
 			headers: {
 				type: Object
 			}
 		},
 		data() {
 			return {
 				dialogImageUrl: '',
 				dialogVisible: false,
 			}
 		},
 		methods: {
 			// 上传图片之前的检查
 			handleBeforeUpload(file) {
 				let reg = /^image\/(jpe?g|png|if)$/;
 				const isImg = reg.test(file.type);
 				const isLt2M = file.size / 1024 / 1024 < 1;
 				if (!isImg) {
 					this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
 				}
 				if (!isLt2M) {
 					this.$message.error('上传头像图片大小不能超过 2MB!');
 				}
 				return isImg && isLt2M;
 			},
 			// 变成数组转字符串
 			strSlider(arr) {
 				let dataString = [];
 				arr.forEach((item, index) => {
 					if (item.response) {
 						dataString.push(item.response.src);
 					} else {
 						dataString.push(item.url);
 					}
 				})
 				return dataString.join();
 			},
 			// 上传图片成功
 			handleUploadSuccess(res, file, filelist) {
 				let _filelist = this.strSlider(filelist)
 				this.$emit('sliderSuccess', _filelist);
 			},
 			// 放大图片
 			handlePictureCardPreview(file) {
 				this.dialogImageUrl = file.url;
 				this.dialogVisible = true;
 			},
 			// 上传图片失败
 			handleUploadError({ status, message }, file, fileList) {
 				switch (status) {
 					case 401:
 						this.$message.error(`错误:401,Token失效,请重新登录!`);
 						break;
 					case 400:
 						message = JSON.parse(message);
 						this.$message.error(`错误:400,${message}`);
 						break;
 					default:
 						this.$message.error(`错误:${status},${message}!`);
 						break;
 				}
 			},
 			// 删除现有图片
 			async handleDel(file, filelist) {
 				if (file.response) {
 					var url = file.response.src;
 				} else {
 					var url = file.url;
 				}
 				// 如果不是默认头像，物理删除图片
 				let { status } = await axios.delete(this.removeAction, { params: { src: url } });
 				if (status) {
 					this.$message.success('删除成功!');
 					let _filelist = this.strSlider(filelist)
 					//filelist 就是删除后数组结果 再把数组传出去
 					this.$emit("sliderSuccess", _filelist);
 				}
 
 			}
 		}
 	};
 </script>
 
 <style lang="less">
 	.el-dialog {
 		width: 490px;
 	}
 </style>
 